/**
 * OSS is a Open Service Container which gives the leverage of building the Desktop and Web
 * Application. * Copyright (C) 2008-2009  Ponraj Sutanthiramani
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Or5e Open Source Community
 * 105, S.S Paradise Apartment, Munnireddy Layout, Horamavu, Banaswadi, Bangalore, India.
 */
package org.or5e.api.webcam.util;

import java.io.*;

/**

 The purpose of this class it to provide some
 useful methods for auto-creating HTML documents.

*/

public class Html {

  public static String NAME = "Page created by algoval.table.Html";
  String name; // the name of the document

  public String bg = "FFFFFF";
  public String text = "000000";
  PrintStream ps;

  public Html(PrintStream ps) {
    this(ps, NAME);
  }

  public static String parseFile(String tag, String filename) {
    try {
      return parseStream(tag, new DataInputStream(new FileInputStream(filename)));
    }
    catch(Exception e) {
      return "Content not found: " + e;
    }
  }

  public static String parseFile(String tag, File file) {
    try {
      return parseStream(tag, new DataInputStream(new FileInputStream(file)));
    }
    catch(Exception e) {
      return "Content not found: " + e;
    }
  }

  /**
    Extracts the body of text between a start and end tag of the specified name
  */
  public static String parseStream(String tag, DataInputStream dis) throws Exception {
    String start = "<" + tag;
    String end = "</" + tag;
    String line;
    while( ((line = dis.readLine()) != null) && (!line.startsWith(start)) );
    String content = "";

    while( ((line = dis.readLine()) != null) && (!line.startsWith(end)) ) {
      content += line + "\n";
    }
    return content;
  }

  public Html(PrintStream ps, String name) {
    this.name = name;
    this.ps = ps;
  }

  public void printHeader() {
    printHeader(ps);
  }

  // <a href="file:///C:/Cafe/packages/plot/Notes.html">These</a>
  public static String anchor(String name, String url) {
    return "<a href=" + translateSpaces(url) + ">" + name + "</a>";
  }

  /** this one does not translate the spaces */
  public static String plainAnchor(String name, String url) {
    return tagContent("a", "href=?" + url + "?",  name );
  }

  public static String image(String url) {
    // <img src="This1.jpg" width="92" height="55" alt="This1.jpg (3732 bytes)">
    // ignore width and height but retain alt tag

    return "<img src=\"" + url + "\" alt=\"" + url + "\">";
  }

  public void printHeader(PrintStream ps) {
    ps.println("<HTML>");
    ps.println("<HEAD>");
    ps.println("<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=iso-8859-1\">");
//    ps.println("<META NAME=\"GENERATOR\" CONTENT=\"Mozilla/4.05 [en] (Win95; I) [Netscape]\">");
    ps.println("<TITLE>" + name + "</TITLE>");
    ps.println("</HEAD>");
    ps.println("<BODY bgcolor=" + bg + " text=" + text + ">");
  }
// <body background="../../controls/PP20.JPG" bgcolor="#000080" text="#000000">

  public void printFooter() {
    printFooter(ps);
  }

  // of course - should really use
  // a more general String replacesment routine

  public static String translateSpaces(String s) {
    // changes each space in a String to have no spaces
    return translateSpaces(s, 0);
  }

  public static String translateSpaces(String x, int i) {
    // iterate through x finding all occurrences
    // of %20 - build a new string that replaces

    // these with spaces
    String space = " ";
    String replace = "%20";

    int occ = x.indexOf(space, i);
    if (occ != -1) {
      int skipTo = occ + space.length();
      return x.substring(i, occ) + replace +
             translateSpaces(x, skipTo);
    }
    else {
      return x.substring(i, x.length());
    }
  }

  public void paragraph(String s) {
    ps.println("<p> "+ s + "</p>");
  }

  public static String makeParagraph(String s) {
    return "<p> "+ s + "</p>";
  }

  public static String beginTag(String tag) {
    return "<" + tag + ">";
  }

  public static String beginTag(String tag, String modifiers) {
    return "<" + tag + " " + convertModifiers(modifiers) + " >";
  }

  public static String convertModifiers(String m) {
    return m.replace('?', '\"');
  }

  public static String endTag(String tag) {
    return "</" + tag + ">";
  }

  public static String tagContent(String tag, String content) {
    return beginTag(tag) + content + endTag(tag);
  }

  public static String tagContent(String tag, String modifiers, String content) {
    return beginTag(tag, modifiers) + content + endTag(tag);
  }

  public void printFooter(PrintStream ps) {
    ps.println("</body>");
    ps.println("</html>");
  }

  public void table(String[] cols, String[][] data) {
    table(cols, data, "Caption would be here");
  }

  public void table(String[] cols, String[][] data, String caption) {
    table(cols, data, caption, null);
  }

  public void table(
    String[] cols, String[][] data, String caption, String[] colors)
  {
    int columns = cols.length;
    int rows = data.length;
    ps.println("<TABLE BORDER COLS=" + columns + " WIDTH=\"100%\" >");
    ps.println("<CAPTION><B><FONT COLOR=\"#000099\"><FONT SIZE=+1>"+caption+"</FONT></FONT></B></CAPTION>");
    ps.println("<TR>");

    for(int i=0; i<columns; i++){
      ps.print("    <TD ALIGN =");
      // column alignment test to go here
      if(true)
        ps.print("CENTER"); // "LEFT" // "RIGHT"
      ps.print(" > ");
      ps.print("<B>" + cols[i] + "</B>");
      ps.print("</TD>");
      ps.println("");
    }

    ps.println("</TR>");
    for(int i=0; i<rows; i++){
      ps.println("<TR>");
      for(int j=0;j<columns;j++){
        ps.print("    <TD ALIGN =");
        if(true)
          ps.print("CENTER"); // "LEFT" // "RIGHT"
        if (colors != null) {
          ps.print(" bgcolor=\"#" + colors[i] + "\"");
          // Wait.Input();
        }
        ps.print(" > ");
        try {
          ps.print(data[i][j]);
        }
        catch(ArrayIndexOutOfBoundsException e) {
          ps.println("?");
        }
        ps.print("</TD>");
        ps.println("");
      }
      ps.println("</TR>");
    }
    ps.println("</TABLE>");
  }



  public void figureImage(String image, String title, String caption, String bgColor) {
    figureContent(image(image), title, caption, bgColor);
  }

  public void figureContent(String content, String title, String caption, String bgColor) {
    ps.println(
      "<table border=\"0\" width=\"100%\" " +
      "cellspacing=\"0\" cellpadding=\"0\" bgcolor=\"" +
      bgColor + "\">");
    ps.println("<tr> <td align=\"center\">" + strong(font(title, "Arial")) + " </td> </tr>");
    ps.println("<tr> <td align=\"center\">" + content + " </td> </tr>");

    if ((caption != null) && (!caption.equals("")))
      ps.println("<tr> <td align=\"center\">" + font(caption, "Arial") + " </td> </tr>");
    ps.println("</table>");
  }

  public String font(String text, String face) {
    return "<font face=\"" + face + "\">" + text + "</font>";
  }

  public String strong(String text) {
    return "<strong> " + text + "</strong>";
  }


  public static void main(String[] args) throws Exception {
    PrintStream ps = new PrintStream(new FileOutputStream("test.html"));
    Html h = new Html(ps, "Pretty Image Page");
    h.printHeader();
    ps.println("Hello world");
    ps.println(anchor("View Source", "Html.html"));

    // for the pretty image, give an Image url, a title, a caption and a background
    // String caption = "Note how the GIF figure appears to look pretty good.  The explanatory text is probably best not centered";
    // String caption = "Caption goes here";
    String caption = null;

    h.figureImage("consTest.gif", "GIF Plot Example", caption,
                  "00FFCC");

    h.printFooter();
    ps.close();
  }
}
